
import React from 'react'
import ReactDOM from 'react-dom'

import { DateField, Calendar } from 'react-date-picker'
import * as UnitAction  from '../../actions/UnitAction'
import { connect }  from 'react-redux'
import _ from 'lodash'


class WorkCreate extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      data: {},
      showList: false
    }
  }

  componentDidMount() {
    this.$unitList = $(ReactDOM.findDOMNode(this.refs.unitLists))
    this.$WorkCreateContent = $(ReactDOM.findDOMNode(this.refs.WorkCreateContent))

  }

  componentDidUpdate () {
    var units = this.props.data;
    var self = this;
    if (units && units.success) {
      if (units.data.length == 0 || !this.state.showList) {
        this.$unitList.hide();
      }else if (!this.state.data.unit_desc || this.state.data.unit_desc.trim() == ''){
        this.$unitList.hide();
      }
      else {
        this.$unitList.show();
      }
    }else {
      this.$unitList.hide();
    }
  }

  onUnitNumberChange(event) {
    var value = $(event.target).val();
    var data = this.state.data;
    data.unit_desc = value;
    this.setState({
      data: data,
      showList: true
    })
    this.props.dispatch(
      UnitAction.loadUnitsAsync({unit_desc: value})
    )
  }

  onUnitNumberClick(event) {
    var value = $(event.target).html();
    var data = this.state.data;
    data.unit_desc = value;
    this.setState({
      data: data,
      showList: false
    })
  }

  onChange(key, dateString) {
    var data = this.state.data
    data[key] = dateString
    this.setState({
      data: data
    })
  }

  onCreateSubmit() {
    var p_start = this.state.data.p_start,
        p_end = this.state.data.p_end,
        owner = this.state.data.owner,
        mobile = this.state.data.mobile,
        content = this.state.data.content,
        priority = this.state.data.priority,
        work_type = this.state.data.work_type,
        public_area = this.state.data.public_area

    if (!owner || owner.length == 0) {
      alert("请输入联系人!")
      return
    }

    if (!mobile || mobile.length == 0) {
      alert("请输入联系电话!")
      return
    }

    if (!content || content.length == 0) {
      alert("请输入内容!")
      return
    }

    var start, end
    if (p_start) {
      start = new Date(p_start)
    }

    if (p_end) {
      end = new Date(p_end)
    }

    if (!start || !this.checkDate(start)) {
      alert("请选择预计开始时间!")
      return
    }

    if (end && this.checkDate(end)) {
      if (end.getTime() - start.getTime() < 0) {
        alert("选择的结束时间比开始时间早!")
        return
      }
    }
    // if (!end || !this.checkDate(end)) {
    //   alert("请选择预计结束时间!")
    //   return
    // }

    if (priority < 1 || priority > 4) {
      alert("请选择优先级!")
      return
    }

    if (work_type < 1 || work_type > 5) {
      alert("请选择类型!")
      return
    }

    var sys_user_id = this.props.sysUser.id
    var data = _.assign(this.state.data, {sys_user_id: sys_user_id})
    this.props.onCreateSubmit(data)
    this.setState({
      data: {
        p_start: p_start,
        p_end: p_end
      }
    })
  }

  pad(n) {
    return n < 10 ? "0"+n : n;
  }


  checkDate(d) {
    if ( Object.prototype.toString.call(d) === "[object Date]" ) {
      // it is a date
      if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
        // date is not valid
        return false
      }
      else {
        // date is valid
        return true
      }
    }
    else {
      // not a date
      return false
    }
  }

  renderUnitList() {
    var units = this.props.data
    var self = this;
    if (units.success) {
      if (units.data.length == 0 || !this.state.showList) {
        // this.$unitList.hide();
        return ""
      }else if (!this.state.data.unit_desc || this.state.data.unit_desc.trim() == ''){
        // this.$unitList.hide();
        return ""
      }
      else {
        // this.$unitList.show();
        return units.data.map(function(data) {
          return (
            <li className="list-group-item"
                onClick={(event)=>self.onUnitNumberClick(event)}>{data.unit_desc}</li>
          )
        })
      }
    }else {
      return "";
    }
  }

  renderWorker() {
    var self = this
    if (!this.props.sysUser.WorkingProperty.isjde) {
      return (
        <div>
          <div className="form-group">
            <label for="workUnit">维修人员</label>
            <input ref="workUnit" type="text" className="form-control"
                    id="workUnit" placeholder="维修人员" value={this.state.data.worker_name}
                    onChange={(event)=>this.onChange("worker_name", $(event.target).val())}
                    />
          </div>
          <div className="form-group">
            <label for="workUnit">维修人电话</label>
            <input ref="workUnit" type="text" className="form-control"
                    id="workUnit" placeholder="维修人电话" value={this.state.data.worker_phone}
                    onChange={(event)=>this.onChange("worker_phone", $(event.target).val())}
                    />
          </div>
        </div>
      )
    }else {
      return ""
    }
  }

  render() {
    var self = this;
    var now = new Date()
    var defaultDate = ""
    // var defaultDate = now.getFullYear()+"-"+this.pad((now.getMonth()+1))+"-"+this.pad(now.getDate())
    //                   +" "+this.pad(now.getHours())+":"+(this.pad(now.getMinutes()))
    // console.log(defaultDate)
    var data = self.state.data;
    var priority
    if (data.priority == 4) {
      priority = "低"
    }else if (data.priority == 3) {
      priority = "中"
    }else if (data.priority == 2) {
      priority = "高"
    }else if (data.priority == 1) {
      priority = "紧急"
    }
    var work_type = ""
    switch(data.work_type){
      case 1:
        work_type = "房屋类故障";break;
      case 2:
        work_type = "给排类故障"; break;
      case 3:
        work_type = "空调类故障"; break;
      case 4:
        work_type = "强电类故障"; break;
      case 5:
        work_type = "弱点类故障"; break;
      default:
        break;
    }
    return (
      <div className="modal fade work-detail" id="work-detail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 className="modal-title" id="WechatUser-modal-label">新建报修</h4>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label for="Delivery-name">户号</label>
                <input ref="DeliveryName" type="text" className="form-control"
                        id="Delivery-name" placeholder="户号" value={this.state.data.unit_desc}
                        onChange={(event)=>this.onUnitNumberChange(event)} />
                <div className="unit-lists" ref="unitLists">
                  <ul className="list-group">
                    {this.renderUnitList()}
                  </ul>
                </div>
              </div>
              <div className="form-group">
                <label for="workUnit">公共区域</label>
                <input ref="workUnit" type="text" className="form-control"
                        id="workUnit" placeholder="公共区域" value={this.state.data.public_area}
                        onChange={(event)=>this.onChange("public_area", $(event.target).val())}
                        />
              </div>
              <div className="form-group">
                <label for="workUnit">联系人姓名</label>
                <input ref="workUnit" type="text" className="form-control"
                        id="workUnit" placeholder="联系人姓名" value={this.state.data.owner}
                        onChange={(event)=>this.onChange("owner", $(event.target).val())}
                        />
              </div>
              <div className="form-group">
                <label for="workUnit">联系人电话</label>
                <input ref="workUnit" type="text" className="form-control"
                        id="workUnit" placeholder="联系人电话" value={this.state.data.mobile}
                        onChange={(event)=>this.onChange("mobile", $(event.target).val())}
                        />
              </div>

              <div className="form-group">
                <label for="workUnit">报修内容</label>
                <textarea ref="WorkCreateContent" type="text" className="form-control"
                        id="workUnit" placeholder="报修内容" value={this.state.data.content || ""}
                        onChange={(event)=>this.onChange("content", $(event.target).val())}
                        />
              </div>
              <div className="form-group">
                <label for="workUnit">预计开始时间</label>
                <div className="">
                  <DateField
                    defaultValue={defaultDate}
                    locale='zh-cn'
                    dateFormat="YYYY-MM-DD HH:mm"
                    onChange={(dateString)=>this.onChange("p_start", dateString)}
                  />
                </div>
              </div>
              <div className="form-group">
                <label for="workUnit">预计结束时间</label>
                <div className="">
                  <DateField
                    defaultValue={defaultDate}
                    locale='zh-cn'
                    dateFormat="YYYY-MM-DD HH:mm"
                    onChange={(dateString)=>this.onChange("p_end", dateString)}
                  />
                </div>
              </div>
              <div className="form-group">
                <label for="workUnit">优先级</label>
                  <div>
                    <div className="btn-group">
                      <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown">
                        <span className="caret"></span>
                        <span>{priority || "优先级"}</span>
                      </button>
                      <ul className="dropdown-menu" role="menu">
                        <li><a onClick={(event)=>this.onChange("priority", 1)}>紧急</a></li>
                        <li><a onClick={(event)=>this.onChange("priority", 2)}>高</a></li>
                        <li><a onClick={(event)=>this.onChange("priority", 3)}>中</a></li>
                        <li><a onClick={(event)=>this.onChange("priority", 4)}>低</a></li>
                      </ul>
                    </div>
                  </div>
              </div>
              <div className="form-group">
                <label for="workUnit">故障类型</label>
                  <div>
                    <div className="btn-group">
                      <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown">
                        <span className="caret"></span>
                        <span>{work_type || "类型"}</span>
                      </button>
                      <ul className="dropdown-menu" role="menu">
                        <li><a onClick={(event)=>this.onChange("work_type", 1)}>房屋类故障</a></li>
                        <li><a onClick={(event)=>this.onChange("work_type", 2)}>给排类故障</a></li>
                        <li><a onClick={(event)=>this.onChange("work_type", 3)}>空调类故障</a></li>
                        <li><a onClick={(event)=>this.onChange("work_type", 4)}>强电类故障</a></li>
                        <li><a onClick={(event)=>this.onChange("work_type", 5)}>弱点类故障</a></li>
                      </ul>
                    </div>
                  </div>
              </div>
              {this.renderWorker()}
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-default" data-dismiss="modal">取消</button>
              <button type="button" className="btn btn-primary"
                    onClick={(event)=> this.onCreateSubmit()}>保存</button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    data: state.units
  }
}

export default connect(mapStateToProps)(WorkCreate)
